﻿using System.ServiceModel;
using System.ServiceModel.Discovery;
using Hippo.Agent.Lib.ControlService;

namespace Hippo.Agent.Lib
{
    public class EndpointDiscovery : IEndpointDiscovery
    {
        private readonly AgentConfigurationProfile configuration;

        public EndpointDiscovery(AgentConfigurationProfile configuration)
        {
            this.configuration = configuration;
        }

        public EndpointAddress Discover()
        {
            var result = GetFromConfiguration();
            
            if (result == null)
            {
                result = SearchAndDiscoverConsole();
            }

            return result;
        }

        private EndpointAddress GetFromConfiguration()
        {
            if (string.IsNullOrEmpty(configuration.ConsoleEndpointAddress))
            {
                return null;
            }

            return new EndpointAddress(configuration.ConsoleEndpointAddress);
        }

        private EndpointAddress SearchAndDiscoverConsole()
        {
            FindResponse response = null;
            while (response == null || response.Endpoints.Count == 0)
            {
                using (var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint()))
                {
                    response = discoveryClient.Find(new FindCriteria(typeof(HippoConsoleControl)));
                }
            }

            var endpointAddress = response.Endpoints[0].Address;
            System.Console.WriteLine(@"Found endpoint at {0}", endpointAddress);

            return response.Endpoints[0].Address;
        }
    }
}
